package com.daqian.cloud.oauth2.service;

import com.daqian.cloud.oauth2.entity.Member;
import com.daqian.cloud.oauth2.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户信息服务
 * 实现 Spring Security的UserDetailsService接口方法，用于身份认证
 */
@Service
public class ChanceUserDetailsService implements UserDetailsService {

    /**
     * 账户数据操作接口
     */
    @Autowired
    private MemberRepository memberRepository;

    /**
     * 授权的时候是对角色授权，而认证的时候应该基于资源，而不是角色，因为资源是不变的，而用户的角色是会变的
     * <p>
     * 根据用户名查找账户信息并返回用户信息实体
     *
     * @param username 用户名
     * @return 用于身份认证的 UserDetails 用户信息实体
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("收到的账号" + username);
        Member account = memberRepository.findByUserName(username);
        if (account == null) {
            throw new UsernameNotFoundException(username);
        }
        return new User(account.getUserName(), account.getPassWord(), AuthorityUtils.commaSeparatedStringToAuthorityList(account.getRoles()));
//        return new User(account.getUserName(), account.getPassWord(), Collections.EMPTY_SET);
    }
}
